package work.xiaohong.arithmetic.IO;

import lombok.Cleanup;
import work.xiaohong.arithmetic.entity.User;

import java.io.*;

/**
 * @author xiaohong
 * @version 1.0
 * @date 2021/10/27 0027 12:44
 * @description 对象流
 * 增强了缓冲区的功能 增强了读写8中基本数据类型和字符串的功能 增强了读写对象的功能
 */
public class ObjectStream {

    public static void main(String[] args) throws Exception {
//        writeFile();
//        readFile();
        copyFile();
    }

    // 序列化 序列化多个可以借助集合
    public static void writeFile() throws Exception {
        // 后面的参数表示是否要子在原来的内容后面追加新内容
        FileOutputStream fileOutputStream = new FileOutputStream("a.txt",true);
        @Cleanup
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);

        // 能够序列化的对象都要实现Serializable接口
        User xiaohong = new User("xiaohong", 18);
        objectOutputStream.writeObject(xiaohong);

    }


    // 反序列化
    public static void readFile() throws Exception {
        FileInputStream fileInputStream = new FileInputStream("a.txt");
        @Cleanup
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

        System.out.println(objectInputStream.readObject());
    }


    // 复制文件
    public static void copyFile() throws Exception {
        FileInputStream fileInputStream = new FileInputStream("a.txt");
        @Cleanup
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        FileOutputStream fileOutputStream = new FileOutputStream("b.txt",true);
        @Cleanup
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(objectInputStream.readObject());
    }

}
